// Copyright (C) 1998-2008, Sumisho Computer Systems Corp. All Rights Reserved.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @author Hitoshi Okada
 */

package com.curlap.orb.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import com.curlap.orb.io.SerializableStreamWriter;
import com.curlap.orb.io.SerializerException;
import com.curl.io.serialize.types.ByteArray;

/**
 * BinaryFileStreamWriter
 */
public class BinaryFileStreamWriter 
{

    // write
    public static void write(String url, int bufferSize, SerializableStreamWriter writer) throws IOException
    {
        FileInputStream stream = null;
        try 
        {
            byte[] bytes = new byte[bufferSize];
            stream = new FileInputStream(new File(url));
            int block;
            while((block = stream.read(bytes)) != -1)
            {
                if (block < bytes.length)
                {
                    byte[] distBytes = new byte[block];
                    System.arraycopy(bytes, 0, distBytes, 0, block);
                    bytes = distBytes;
                }
                writer.write(new ByteArray(bytes));
            }
        }
        catch (FileNotFoundException e)
        {
            throw new IOException(e.getMessage());
        }
        catch (SerializerException e)
        {
            throw new IOException(e.getMessage());
        }
        finally
        {
            if (writer != null)
            {
                try
                {
                    writer.close();
                }
                catch (SerializerException e)
                {
                    throw new IOException(e.getMessage());
                }
            }
            if (stream != null)
                stream.close();
        }
    }
    
    // write as buffer size = 8192
    public static void write(String url, SerializableStreamWriter writer) throws IOException
    {
        write(url, 8192, writer);
    }
}
